#pragma once

#include "INetworkChannel.h"
#include "MessagePool.h"
#include <asio.hpp>
#include <deque>
#include <mutex>
#include <thread>
#include <atomic>
#include <memory>
#include <vector>
#include <shared_mutex>
#include <string>
#include <functional>

namespace SeanNetwork {

/**
 * @brief Base class for network channel implementations.
 * 
 * Implements common functionality shared between different channel types,
 * using the Template Method pattern for connection lifecycle.
 */
class BaseNetworkChannel : public INetworkChannel {
public:
    BaseNetworkChannel(asio::io_context& ioContext);
    ~BaseNetworkChannel() override;

    // INetworkChannel interface implementation
    bool Initialize() override;
    bool Connect(const std::string& host, uint16_t port) override;
    void Disconnect() override;
    bool SendMsg(std::shared_ptr<NetworkMessage> message) override;
    void SetMessageCallback(MessageReceiveCallback callback) override;
    void SetConnectionCallback(ConnectionStateCallback callback) override;
    ConnectionState GetConnectionState() const override;
    NetworkStats GetNetworkStats() const override;
    uint32_t GetLatency() const override;
    void Update() override;

protected:
    // Template methods to be implemented by derived classes
    virtual bool DoInitialize() = 0;
    virtual bool DoConnect(const std::string& host, uint16_t port) = 0;
    virtual void DoDisconnect() = 0;
    virtual void DoSendMessage(std::shared_ptr<NetworkMessage> message) = 0;
    virtual void DoUpdate() = 0;
    
    // Common functionality available to derived classes
    void UpdateConnectionState(ConnectionState newState, const std::string& reason = "");
    void UpdateNetworkStats(uint64_t bytesSent, uint64_t bytesReceived, bool messageSent, bool messageReceived);
    void UpdateRtt(uint32_t rtt);
    uint32_t CalculateReconnectDelay() const;
    void HandleMessageAck(uint32_t messageId, bool success);
    
    // 线程安全地访问回调
    void InvokeMessageCallback(std::shared_ptr<NetworkMessage> message);
    void InvokeConnectionCallback(ConnectionState state, const std::string& reason);
    
    // Common member variables
    asio::io_context& m_IoContext;
    asio::strand<asio::io_context::executor_type> m_Strand;
    
    std::atomic<ConnectionState> m_State;
    std::string m_Host;
    uint16_t m_Port;
    
    // 回调相关
    mutable std::shared_mutex m_CallbackMutex; // 使用读写锁保护回调
    MessageReceiveCallback m_MessageCallback;
    ConnectionStateCallback m_ConnectionCallback;
    
    std::unique_ptr<MessagePool> m_MessagePool;
    NetworkStats m_Stats;
    
    mutable std::mutex m_StatsMutex;
    std::mutex m_SendQueueMutex;
    
    std::deque<std::shared_ptr<NetworkMessage>> m_SendQueue;
    
    // Reconnection variables
    uint32_t m_ReconnectInitialDelay;  // 初始重连延迟（毫秒）
    uint32_t m_ReconnectMaxDelay;      // 最大重连延迟（毫秒）
    uint32_t m_ReconnectMaxAttempts;   // 最大重连尝试次数
    uint32_t m_ReconnectAttempts;      // 当前重连尝试次数
    
    // Latency tracking
    std::vector<uint64_t> m_RttSamples;    // RTT采样数据
    
    // Timer management
    virtual void StartReconnect() = 0;
    virtual void SendKeepAlive() = 0;

    // 辅助方法：将连接状态转为字符串
    std::string ConnectionStateToString(ConnectionState state);
};

} // namespace SeanNetwork 
